package com.easycms.base;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;

import org.imgscalr.Scalr;

public class BaseMain {
	private static int THUMB_WIDTH = 77;
	private static int THUMB_HEIGHT = 57;
	public static void main(String[] args) {
		
		try {
			scaleAndSaveImageWithScalr("d:\\attach\\111111.jpg", "d:\\attach\\t111111.jpg", THUMB_WIDTH, THUMB_HEIGHT);
			scaleAndSaveImageWithScalr("d:\\attach\\111112.jpg", "d:\\attach\\t111112.jpg", THUMB_WIDTH, THUMB_HEIGHT);
			scaleAndSaveImageWithScalr("d:\\attach\\111113.jpg", "d:\\attach\\t111113.jpg", THUMB_WIDTH, THUMB_HEIGHT);
			scaleAndSaveImageWithScalr("d:\\attach\\111114.jpg", "d:\\attach\\t111114.jpg", THUMB_WIDTH, THUMB_HEIGHT);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void scaleAndSaveImageWithScalr(String sourceFile, String destFile,
			int width, int height) throws IOException {
		BufferedImage sourceImage = ImageIO.read(new File(sourceFile));
		BufferedImage destImage = Scalr.resize(sourceImage,
				Scalr.Method.QUALITY, width, height);
		writeJpeg(destImage, destFile, 0.9f);
	}

	private static  void writeJpeg(BufferedImage image, String destFile, float quality)
			throws IOException {
		ImageWriter writer = null;
		FileImageOutputStream output = null;
		try {
			writer = ImageIO.getImageWritersByFormatName("jpeg").next();
			ImageWriteParam param = writer.getDefaultWriteParam();
			param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
			param.setCompressionQuality(quality);
			output = new FileImageOutputStream(new File(destFile));
			writer.setOutput(output);
			IIOImage iioImage = new IIOImage(image, null, null);
			writer.write(null, iioImage, param);
		} catch (IOException ex) {
			throw ex;
		} finally {
			if (writer != null)
				writer.dispose();
			if (output != null)
				output.close();
		}
	}
}
